<template>
  <div>
    <div
      v-loading="isLoading"
      style="height: calc(100% - 20px)"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <div class="top_llfxChart">
        <el-form class="m-t-10" ref="ruleForm" label-width="60px" label-position="top">
          <p class="datesech">
             <span class="sechsp">时间选择</span>
            <el-form-item label="" style="margin: 0px 0 5px 0">
              <el-date-picker
                v-model="TimeRain"
                type="datetimerange"
                prefix-icon="el-icon-date"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 99%"
                range-separator="至"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                :default-time="[timebeg, timeend]"
                @change="selectTime(TimeRain)"
              />
               <!-- <span class="sechbtn" @click.stop="selectTime(TimeRain)"><i class="el-icon-search"></i></span> -->
            </el-form-item>
          </p>
        </el-form>
        <div class="RightCardTitle">村庄预警统计</div>
         <el-row class="echartCont" >
         <el-col :span="11" style="height:100%">
           <div id="JcyjChart" style="height:100%;width: 100%;"  />
         </el-col>
         <el-col :span="13">
          <!-- ['#ce1f1f', '#f0810b', '#f0c90b', '#00a2fb'] -->
        <div class="chartopdv">
          <p class="charp" v-for="(item,ind) in echarlist" :key="ind">
            <span class="charpsp1" :class="'bacol'+ind"></span>
            <span class="charpsp2">{{item.Txt}}</span>
            <span class="charpsp3">{{item.value}}</span>
            <span class="charpsp4">{{item.percent}}%</span>
          </p>
        
        </div>
       </el-col>
         </el-row>
      </div>
      <div class="tableBox">
        <div class="RightCardTitle">村庄预警详情</div>
        <template v-if="StatisticsList.length>0">
          <el-collapse accordion v-model="activeNames" class="collapse_div">
            <el-collapse-item class="m-t-5"
              v-for="(item, index) in StatisticsList"
              :key="index"
              :name="index"
              :class="'warningLevel' + item.Lvl"
            >
              <template slot="title">
                {{ item.Txt }} <span class="rightTitle">  <span>{{ item.Count }}</span>个村庄</span>
              </template>
              <div class="stationLst">
                 <div class="titleList m-t-5">
                  <span>村庄名称</span>
                  <span>防汛责任人</span>
                  <span>预警时间</span>
                </div>
                <ul class="stationLstul">
                  <template v-if="item.Detail.length > 0">
                    <li class="m-t-5"
                      v-for="(itemDetailList, indexDetailList) in item.Detail"
                      :key="indexDetailList"
                      :class="{ tableBgList: selectNum == item.Lvl+'-'+indexDetailList }"
                      @click="onClickShowDetail(itemDetailList,item.Lvl+'-'+indexDetailList)"
                    >
                      <span>{{ itemDetailList.Village }}</span>
                      <span>{{ itemDetailList.UserName }}</span>
                      <span>{{ $moment(itemDetailList.Ftm).format("MM-DD HH:mm") }}</span>
                    </li>
                  </template>
                  <template v-else>
                    <div class="noDataLists">暂无数据</div>
                  </template>
                </ul>
              </div>
            </el-collapse-item>
          </el-collapse>
        </template>
        <template v-else>
          <div class="noDataLists">暂无数据</div>
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import {
    GetMonitoringWarningStatistics
} from '@/api/zyx.js'
// 风险预警模块
import YJ_JC from '../../../../map/cesium/mixins/YJ_JC'
export default {
    mixins: [YJ_JC],
    data() {
        return {
            selectNum: -1,
            ruleForm: {
                wswscd: '',
                dtBegin: this.$store.getters.startTimeCommon,//this.$moment().subtract(3, 'hour').format('YYYY-MM-DD HH:mm'),
                dtEnd: this.$store.getters.endTimeCommon,//this.$moment().format('YYYY-MM-DD HH:mm')
            },
            timebeg: this.$moment(this.$store.getters.startTimeCommon).format('HH:mm:ss'),
            timeend: this.$moment(this.$store.getters.endTimeCommon).format('HH:mm:ss'),
            StatisticsList: [],
            pieData: [],
            TimeRain: [this.$store.getters.startTimeCommon, this.$store.getters.endTimeCommon],
            isLoading: false,
            thirdvillageAdcd:"",//省平台的村庄编码
            activeNames:'',
            echarlist:[],

        }
    },
    computed: {
        isFollow() {
            return this.$store.getters.basin
        }
    },
    watch: {
        isFollow: {
            immediate: true,
            deep: true,
            handler(val) {
               // console.log(val)
                this.ruleForm.wswscd = val
                this.resetList();//重新刷新页面数据
                this.villageLocat();//村庄定位
            }
        }

    },
    created() {
        // this.getDataJcyj()
    },
    methods: {
      //村庄定位
      villageLocat(){
      //  console.log(this.$store.getters.thirdPageUser)
        let thirdPageUser = this.$store.getters.thirdPageUser;
       // console.log(thirdPageUser)
        
        if(thirdPageUser.villageAdcd){//判断有没有村庄 有村庄ID 定位
           this.thirdvillageAdcd = thirdPageUser.villageAdcd;
        };
        let dtBegin = thirdPageUser.dtBegin;
        let dtEnd = thirdPageUser.dtEnd;
        if(dtBegin&&dtEnd){//开始时间和结束时间都有
           this.selectTime([dtBegin,dtEnd],'1');
        }
       
        thirdPageUser.villageAdcd = '';
        //监测预警要带到预演 预演时间
        //thirdPageUser.dtBegin = '';
       // thirdPageUser.dtEnd = '';
        thirdPageUser.tabType = '';
        this.$store.dispatch('setThirdPageUser', thirdPageUser);
       
      },
       //重新刷新页面数据
        resetList() {
          //清空村庄详情列表数据
          this.StatisticsList = [];
          this.activeNames = '';
          this.thirdvillageAdcd = '';
            this.$nextTick(() => {
               this.getDataJcyj()
            })
        },
        selectTime(val,typ) { // 自定义时间   typ 1 判断在省平台带过来
            if (val) {
                this.ruleForm.dtBegin = val[0]
                this.ruleForm.dtEnd = val[1]
                this.TimeRain = val;
                this.$store.dispatch('startTimeCommon', val[0])
                this.$store.dispatch('endTimeCommon', val[1])
                this.getDataJcyj();
               // 保存监测预警时间
              // console.log(this.$store.getters.thirdPageUser)
                if(typ != '1'&&this.$store.getters.thirdPageUser.dtBegin){
                  this.$store.getters.thirdPageUser.dtBegin =  this.ruleForm.dtBegin;
                  this.$store.getters.thirdPageUser.dtEnd = this.ruleForm.dtEnd;

                }
            };
            // console.log(this.$store.getters.thirdPageUser)
        },
        // 点击左侧列表项
        onClickShowDetail(item, index) {
            // 传时间
            console.log('点击左侧列表项',item);
            this.$eventBus.$emit('TK_Date_Card_Click', {
                perioD_END:  item.Ftm,
            })
            this.selectNum = index;
            this.flyToVillShowPopYJJC(item.Ewcode)
        },
        // 获取左侧列表数据
      async getDataJcyj() {
            // this.pieData = []
            this.isLoading = true;
            this.selectNum = '-1';
            this.activeNames = '';
            GetMonitoringWarningStatistics(this.ruleForm).then((res) => {
                const _this = this
                this.isLoading = false
                this.pieData = []
                if (res.isSuccess) {
                    this.StatisticsList = res.data.filter(function(item, index) {
                        return item.Detail.length > 0
                    })
                    res.data.forEach(function(item, index) {
                        _this.pieData.push({
                            value: item.Count,
                            name: item.Txt
                        })
                    })
                    this.getPieEchart();
                    if(this.thirdvillageAdcd){
                      this.findlistdata(this.StatisticsList);
                    }
                    console.log('列表数据：',res);
                    
                    this.$eventBus.$emit('TK_Date_Card_Click', {
                        perioD_END:  res.data[0].Detail[0].Ftm,
                    })
                    // this.StatisticsList = res.data
                } else {
                    this.$message.error(res.message)
                }
            }).catch(err=>{
              this.isLoading = false;
            });
            //地图渲染完数据调用定位村方法
            try { 
              let response = await this.creatYJJC(this.ruleForm,this.thirdvillageAdcd);
               if(this.thirdvillageAdcd){//判断村code 是否存在
                  this.flyToVillShowPopYJJC(this.thirdvillageAdcd);
                   this.thirdvillageAdcd = '';
               };
               response = '';
            }catch (error) {
              console.error(error);
           }
        },
        //查找村庄
        findlistdata(list){
            let villadcd = this.thirdvillageAdcd;
            for(let i=0;i<list.length;i++){
              let childata = list[i].Detail;
              let flg = false;
              childata.forEach((item,inde)=>{
                 if(item.Ewcode == villadcd){
                    // alert(inde);
                     this.selectNum = inde;
                     //定位到地图风险村
                     //this.flyToVillShowPopYJJC(item.Ewcode)
                     flg = true;
                 }
              });
              if(flg){
                this.activeNames = i;
                break;
              }
            };
           
        },
        // 饼图
        getPieEchart() {
            const colorList = ['#CE1F1F', '#F0810B', '#F0C90B', '#1c38a1']
            if (this.myChart) {
                this.myChart.dispose()
            }
            let arlist = this.pieData;
            let total = 0;
            arlist.forEach(item=>{
               total += parseFloat(item.value)
               let txn = item.name.split('（');
               item.Txt = txn[0];
            });
             arlist.forEach(item=>{
               if(total == 0){
                  item['percent'] = 0;
               }else{
                let num  = (parseFloat(item.value) /total) * 100
                if(!/\./.test(num)){//如果没有小数点
                 item['percent'] = num;
                }else{
                  item['percent'] = num.toFixed(1);
                }
               }
            });
            this.echarlist = arlist;
           // console.log(this.echarlist)
            // 饼图
            const option = {
                title: {
                    // 设置饼图标题，位置设为顶部居中
                    text: ''
                },
                 tooltip: {
                    show:false,
                    trigger: 'item',
                    position: ['40%', '40%']
                },
                color: colorList,
                series: [{
                    type: 'pie',
                    radius: ['50%','90%'], // 饼图半径
                   // center: ['50%', '50%'],
                   // roseType: 'area',
                    label: {
                        show: false,
                        color: '',
                        formatter: '{c} \n {b}', // b代表名称，c代表对应值，d代表百分比
                        overflow: 'breakAll',
                        lineHeight: 16
                    },
                    data: this.pieData.map((item, index) => {
                        item.label = {
                            color: colorList[index]
                        }
                        return item
                    })
                }]
            }
            this.$nextTick(() => {
                this.myChart = this.$echarts.init(document.getElementById('JcyjChart'))
                this.myChart.setOption(option)
            })
        }
    }
}
</script>
<style lang="less" scoped>

	.top_llfxChart {
		height: 330px;
    
		.el-input__inner {
			width: 80%;
		}
    .chartsCss{
      height: 220px;
    }
    .echartCont{
      height: 225px;
    }
  }
  .tableBox {
    width: 100%;
    height: calc(100vh - 540px);
    background: rgba(3,34,55,0.4);
    padding: 5px 10px 10px 0px;
    overflow: hidden;
		.collapse_div {
      //height: calc(100vh - 680px);
      height: calc(100% - 55px);
			overflow: auto;
		}
	}
.isShowtopflg{
  .tableBox {
    height: calc(100vh - 480px);

		.collapse_div {
      height: calc(100% - 55px);

		}
	}

}
.datesech{
 .sechsp{
   display:inline-block;
   margin-bottom:5px;
   font-size: 14px;
   color:#fff;
   opacity: 0.8;
 }
  .el-input__inner{
   border: solid 1px #1E73DC;
   background-color:#00377B;
   
  }
  .sechbtn{
    display: inline-block;
    width:14%;
    height:33px;
    margin-left:1%;
    border-radius: 6px;
    background-color:#1E73DC;
    font-size:18px;
    text-align: center;
    color:#fff;
    box-sizing: border-box;
    line-height: 34px;
    cursor: pointer;

  }
}
 .chartopdv{
    width:100%;
    padding-right:5px;
    margin-top:40px;
    box-sizing: border-box;
  }
  .charp{
    width:100%;
    height: 32px;
    background: rgba(0,150,255,0.3);
    line-height: 32px;
    padding-left:5px;
    margin-bottom:20px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-around;
    align-items: center;
    text-align: center;
  }
  .charpsp1{
    display: inline-block;
    width:14px;
    height:14px;
    background:#ce1f1f;
  }
  .charpsp2{
   display: inline-block;
   color: #B2C7D9;
   font-size:14px;
   padding-left: 5px;
   text-align: left;
   flex:3;
  }
  .charpsp3{
   display: inline-block;
   color: #fff;
   font-size:14px;
   flex:2;
  }
  .charpsp4{
   display: inline-block;
   color: #fff;
   font-size:14px;
   flex:2;
  }
  .bacol1{
     background:#f0810b;
  }
  .bacol2{
     background:#f0c90b;
  }
  .bacol3{
     background:#1c38a1;
  }
</style>
